package com.localjoycommunity.cpdj.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.localjoycommunity.cpdj.common.CodeMsg;
import com.localjoycommunity.cpdj.common.exception.GlobalException;
import com.localjoycommunity.cpdj.common.utils.SecurityUtils;
import com.localjoycommunity.cpdj.project.system.domain.*;
import com.localjoycommunity.cpdj.project.system.domain.vo.UserCourseVo;
import com.localjoycommunity.cpdj.project.system.mapper.*;
import com.localjoycommunity.cpdj.project.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author leepandar
 * @date 2020-10-29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAnswerMapper userAnswerMapper;
    @Autowired
    private SysQuestionMapper sysQuestionMapper;
    @Autowired
    private SysPaperMapper sysPaperMapper;
    @Autowired
    private SysPaperQuestionMapper sysPaperQuestionMapper;

    @Autowired
    private UserCourseMapper userCourseMapper;

    /**
     * 绑定微信和手机号
     * todo 如果没有则绑定 有则更新
     *
     * @return
     */
    @Override
    public User bindUser(User user) {
        User one = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone()));
        // 更新用户
        if (one != null) {
            user.setId(one.getId());
            userMapper.updateUser(user);
            return user;
        } else {
            if (user.getName() == null) {
                user.setName(user.getPhone());
            }
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            // 3. 保存数据库
            int insert = userMapper.insert(user);
            if (insert > 0) {
                return user;
            }
            throw new GlobalException(CodeMsg.ACCOUNT_REGISTER_ERROR);
        }

    }

    @Override
    public User registerByPassword(User user) {
        // 1. 检查用户是否存在
        if (phoneExist(user)) {
            throw new GlobalException(CodeMsg.USER_EXIT_ERROR);
        }
        return bindUser(user);
    }

    private boolean phoneExist(User user) {
        User one = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone()));
        if (one != null) {
            return true;
        }
        return false;
    }

    @Override
    public User loginByPassword(String phone, String pwd) {
        User one = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
        if (one == null) {
            throw new GlobalException(CodeMsg.USER_NOT_EXIT_ERROR);
        }
        boolean b = SecurityUtils.matchesPassword(pwd, one.getPassword());
        if (b) {
            return one;
        }
        throw new GlobalException(CodeMsg.USER_NAME_OR_PASSWORD_ERROR);

    }

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public User selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param user 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param user 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertUser(User user) {
        // user.setCreateTime(DateUtils.getNowDate());
        return userMapper.insertUser(user);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param user 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] ids) {
        return userMapper.deleteUserByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id) {
        return userMapper.deleteUserById(id);
    }

    @Override
    public User selectUserByOpenid(String openid) {
        User user = baseMapper.selectOne(new QueryWrapper<User>()
                .lambda().eq(User::getOpenid, openid));
        return user;
    }



    @Override
    public List<User> answerHistory(User user) {
        List<User> userList = userMapper.selectUserList(user);
        for (User user1 : userList) {
            //用户作答试卷数
            List<UserAnswer> userAnswers = userAnswerMapper.selectUserAnswerByUserId(user1.getId());
            if (userAnswers != null && userAnswers.size() > 0) {
                user1.setPaperNum(userAnswers.size());
            }
            //答题总数
            Integer answerNum = 0;
            //对题数
            Integer correctNum = 0;
            //错题数
            Integer wrongNum = 0;
            //总得分
            Integer scoreTotal = 0;
            for (UserAnswer userAnswer : userAnswers) {
                Long wrong = userAnswer.getWrongNum();
                Long correct = userAnswer.getCorrectNum();
                Long score = userAnswer.getScoreTotal();
                Long total = correct + wrong;
                answerNum += total.intValue();
                correctNum += correct.intValue();
                wrongNum += wrong.intValue();
                scoreTotal += score.intValue();
            }
            user1.setAnswerNum(answerNum);
            user1.setCorrectNum(correctNum);
            user1.setWrongNum(wrongNum);
            user1.setScoreTotal(scoreTotal);
        }
        return userList;
    }

    @Override
    public List<UserCourseVo> statisticCourse() {
        return userCourseMapper.statisticCourse();
    }


//    public List<User> answerHistory1(User user) {
//        List<User> userList = userMapper.selectUserList(user);
//        for (User user1 : userList) {
//            //用户作答试卷数
//            List<UserAnswer> userAnswers = userAnswerMapper.selectUserAnswerByUserId(user1.getId());
//            if (userAnswers != null && userAnswers.size() > 0) {
//                user1.setPaperNum(userAnswers.size());
//            }
//            //答题总数
//            Integer answerNum = 0;
//            for (UserAnswer userAnswer : userAnswers) {
//                List<UserAnswer> userAnswers1 = userAnswerMapper.selectUserAnswerByPaperId(userAnswer.getPaperId());
//                if (userAnswers1 != null && userAnswers1.size() > 0) {
//                    answerNum += userAnswers1.size();
//                }
//            }
//            user1.setAnswerNum(answerNum);
//
//            List<UserAnswer> userAnswers2 = userAnswerMapper.selectUserAnswerCorrect(user1.getId());
//            user1.setCorrectNum(userAnswers2 == null ? 0 : userAnswers2.size());
//            //错题数
//            List<UserAnswer> userAnswers3 = userAnswerMapper.selectUserAnswerWrong(user1.getId());
//            user1.setWrongNum(userAnswers3 == null ? 0 : userAnswers3.size());
//            //总得分
//            Integer scoreTotal = 0;
//            if (userAnswers != null && userAnswers.size() > 0) {
//                for (UserAnswer userAnswer : userAnswers) {
//                    Integer score = 0;
//                    SysPaperQuestion sysPaperQuestion = new SysPaperQuestion();
//                    sysPaperQuestion.setPaperId(userAnswer.getPaperId());
//                    List<SysPaperQuestion> paperQuestions = sysPaperQuestionMapper.selectSysPaperQuestionList(sysPaperQuestion);
//                    for (SysPaperQuestion paperQuestion : paperQuestions) {
//                        SysQuestion sysQuestion = sysQuestionMapper.selectSysQuestionById(paperQuestion.getQuestionId());
//                        score += sysQuestion.getScore().intValue();
//                    }
//                    scoreTotal += score;
//                }
//            }
//            user1.setScoreTotal(scoreTotal);
//        }
//        return userList;
//    }
}
